<template>
  <div class="home-page">
    <!-- 顶部主题图片 -->
    <div v-if="themeA?.online" class="top-theme" @click="goToTheme('t-1')">
      <img :src="themeA.entrance_img" alt="主题" />
    </div>

    <!-- 轮播图 -->
    <van-swipe class="banner-swipe" :autoplay="3000" indicator-color="#157658">
      <van-swipe-item v-for="(item, index) in bannerB?.items" :key="index" @click="goToBanner(item)">
        <img :src="item.img" :alt="item.title" />
      </van-swipe-item>
    </van-swipe>

    <!-- 分类网格 -->
    <category-grid :grid="grid" />

    <!-- 活动图片 -->
    <div v-if="activityD" class="activity-banner" @click="goToCoupons('a-2')">
      <img :src="activityD.entrance_img" alt="活动" />
    </div>

    <!-- 测试积分购买链接 -->
    <!-- <div class="test-section" style="margin: 20px; padding: 20px; background: #f0f0f0; border-radius: 8px;">
      <h3 style="margin-bottom: 10px;">测试功能</h3>
      <van-button 
        type="primary" 
        size="small" 
        @click="testPointsOrder"
        style="margin-bottom: 10px;"
      >
        测试积分购买（哪吒2 - SKU ID: 53）
      </van-button>
    </div> -->

    <!-- 主题商品 -->
    <!-- <div v-if="themeE?.online && themeESpu.length > 0" class="theme-spu-section">
      <div class="section-title">
        <img src="/imgs/home/title@interest.png" alt="精选商品" />
      </div>
      <div class="spu-grid">
        <spu-preview
          v-for="spu in themeESpu"
          :key="spu.id"
          :spu="spu"
          @click="goToDetail(spu.id)"
        />
      </div>
    </div> -->

    <!-- 底部商品瀑布流 -->
    <div class="spu-bottom">
      <div class="section-title">
        <img src="/imgs/home/title@interest.png" alt="猜你喜欢" />
      </div>
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadMore"
      >
        <div class="spu-waterfall">
          <spu-preview
            v-for="spu in spuList"
            :key="spu.id"
            :spu="spu"
            @click="goToDetail(spu.id)"
          />
        </div>
      </van-list>
    </div>

    <!-- 底部导航 -->
    <tab-bar />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { 
  getBanners, 
  getCategoryGrid, 
  getThemes, 
  getThemeSpu, 
  getLatestSpu 
} from '@/api/home'
import CategoryGrid from '@/components/category-grid/index.vue'
import SpuPreview from '@/components/spu-preview/index.vue'
import TabBar from '@/components/tab-bar/index.vue'

const router = useRouter()

// 响应式数据
const themeA = ref(null)
const bannerB = ref([])
const grid = ref([])
const activityD = ref(null)
const themeE = ref(null)
const themeESpu = ref([])
const spuList = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(0)

// 初始化数据
const initData = async () => {
  try {
    loading.value = true
    
    // 并行请求数据
    const [bannersRes, categoryGridRes, themesRes] = await Promise.all([
      getBanners('b-1'), // 首页轮播图
      getCategoryGrid(),
      getThemes('t-1,t-2,t-3,t-4') // 首页主题
    ])
    
    bannerB.value = bannersRes.banner_items || []
    grid.value = categoryGridRes || []
    activityD.value = null // 暂时设为null，等activity API实现后再启用

    // 处理主题数据
    if (themesRes) {
      themeA.value = themesRes.find(t => t.name === 't-1')
      themeE.value = themesRes.find(t => t.name === 't-2')
      
      // 获取主题E的商品
      if (themeE.value?.online) {
        const themeSpus = await getThemeSpu(themeE.value.name)
        if (themeSpus) {
          themeESpu.value = themeSpus.spu_list.slice(0, 8)
        }
      }
    }
    
    // 获取最新商品
    await loadLatestSpu()
    
  } catch (error) {
    console.error('获取首页数据失败:', error)
    showToast('获取数据失败')
  } finally {
    loading.value = false
  }
}



// 加载最新商品
const loadLatestSpu = async () => {
  try {
    const res = await getLatestSpu(0, 10)
    
    if (res && res.items) {
      spuList.value = res.items
      currentPage.value = 1
      finished.value = res.items.length < 10
    }
  } catch (error) {
    console.error('获取最新商品失败:', error)
  }
}

// 加载更多商品
const loadMore = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    const start = currentPage.value * 10
    const res = await getLatestSpu(start, 10)
    
    if (res && res.items) {
      spuList.value.push(...res.items)
      currentPage.value++
      
      if (res.items.length < 10) {
        finished.value = true
      }
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('加载商品失败:', error)
    showToast('加载商品失败')
  } finally {
    loading.value = false
  }
}



// 跳转到轮播图目标
const goToBanner = (banner) => {
  if (banner.type === 'spu') {
    router.push(`/detail/${banner.keyword}`)
  } else if (banner.type === 'theme') {
    router.push({
      path: '/theme-spu-list',
      query: { tname: banner.keyword }
    })
  } else if (banner.type === 'spu_list') {
    router.push({
      path: '/spu-list',
      query: { keyword: banner.keyword }
    })
  }
}

// 跳转到优惠券页
const goToCoupons = (activityName) => {
  router.push({
    path: '/coupon',
    query: { name: activityName, type: 'activity' }
  })
}

// 跳转到商品详情
const goToDetail = (spuId) => {
  router.push(`/detail/${spuId}`)
}

// 跳转到分类
const goToCategory = (category) => {
  router.push({
    path: '/spu-list',
    query: { category_id: category.id }
  })
}

// 跳转到主题
const goToTheme = (theme) => {
  router.push({
    path: '/spu-list',
    query: { theme_name: theme.name }
  })
}

// 测试积分购买
const testPointsOrder = () => {
  console.log('测试积分购买：跳转到积分购买页面')
  router.push({
    path: '/points-order',
    query: {
      id: 53, // 哪吒2的SKU ID
      count: 1
    }
  })
}

// 组件挂载时初始化数据
onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.home-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 50px;
  
  // 大屏适配
  @media (min-width: 768px) {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px 50px;
  }
  
  @media (min-width: 1024px) {
    max-width: 1400px;
    padding: 0 40px 50px;
  }
  
  @media (min-width: 1440px) {
    max-width: 1600px;
    padding: 0 60px 50px;
  }
}

.top-theme {
  width: 100%;
  height: 130px;
  
  @media (min-width: 768px) {
    height: 200px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  @media (min-width: 1024px) {
    height: 250px;
  }
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.banner-swipe {
  width: 100%;
  height: 180px;
  
  @media (min-width: 768px) {
    height: 300px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  @media (min-width: 1024px) {
    height: 400px;
  }
  
  :deep(.van-swipe__track) {
    height: 100%;
  }
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.activity-banner {
  margin: 10px 0;
  width: 100%;
  height: 155px;
  
  @media (min-width: 768px) {
    height: 200px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  @media (min-width: 1024px) {
    height: 250px;
  }
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.theme-spu-section {
  background: #fff;
  margin: 10px 0;
  padding: 15px 0;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  @media (min-width: 768px) {
    margin: 20px 0;
    padding: 30px 0;
  }
  
  .section-title {
    text-align: center;
    margin-bottom: 15px;
    
    @media (min-width: 768px) {
      margin-bottom: 30px;
    }
    
    img {
      height: 35px;
      width: auto;
      
      @media (min-width: 768px) {
        height: 50px;
      }
    }
  }
  
  .spu-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 0 15px;
    
    @media (min-width: 768px) {
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      padding: 0 30px;
    }
    
    @media (min-width: 1024px) {
      grid-template-columns: repeat(4, 1fr);
      gap: 25px;
      padding: 0 40px;
    }
    
    @media (min-width: 1440px) {
      grid-template-columns: repeat(5, 1fr);
      gap: 30px;
      padding: 0 50px;
    }
  }
}

.spu-bottom {
  background: #fff;
  margin-top: 10px;
  padding: 15px 0;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  @media (min-width: 768px) {
    margin-top: 20px;
    padding: 30px 0;
  }
  
  .section-title {
    text-align: center;
    margin-bottom: 15px;
    
    @media (min-width: 768px) {
      margin-bottom: 30px;
    }
    
    img {
      height: 35px;
      width: auto;
      
      @media (min-width: 768px) {
        height: 50px;
      }
    }
  }
  
  .spu-waterfall {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 0 15px;
    
    @media (min-width: 768px) {
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      padding: 0 30px;
    }
    
    @media (min-width: 1024px) {
      grid-template-columns: repeat(4, 1fr);
      gap: 25px;
      padding: 0 40px;
    }
    
    @media (min-width: 1440px) {
      grid-template-columns: repeat(5, 1fr);
      gap: 30px;
      padding: 0 50px;
    }
  }
}

// 底部导航大屏适配
:deep(.tab-bar) {
  @media (min-width: 768px) {
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 100%;
    max-width: 1200px;
    border-radius: 12px 12px 0 0;
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  }
  
  @media (min-width: 1024px) {
    max-width: 1400px;
  }
  
  @media (min-width: 1440px) {
    max-width: 1600px;
  }
}
</style> 